// pages/home/publish/index.js
import {
  BASE_URL
} from '../../../constant/index'
import {
  postDynamicApi
} from '../../../https/dynamic'
import {
  $off,
  $on
} from '../../../utlis/eventBus'
import {
  uploadFileAsync
} from '../../../utlis/utils'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    BASE_URL,
    dynamic: {
      desc: '',
      type: 1,
      atlas: [],
      videoUrl: '',
      videoCover: '',
      address: '',
      isShow: 1
    },
    typeList: ['图文', '视频'],
    isShowList: ['仅自己可见', '公开可见'],
    maxLength: 9,
    topicList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    $on('topicEvent', this.topicEvent.bind(this))
  },
  onUnload() {
    $off('topicEvent', this.topicEvent)
  },
  // 输入框o
  changeDesc(e) {
    const value = e.detail.value
    this.setData({
      'dynamic.desc': value
    })
  },
  // 上传图片
  async bindUpload() {
    const maxLength = this.data.maxLength
    const length = this.data.dynamic.atlas.length
    const {
      tempFiles
    } = await wx.chooseMedia({
      count: maxLength - length,
      mediaType: ['image']
    })
    wx.showLoading({
      title: '上传中..',
    })
    const uploadList = tempFiles.map(item => {
      return new Promise(async (resolv) => {
        const url = await uploadFileAsync(item.tempFilePath)
        resolv(url)
      })
    })

    const urlList = await Promise.all(uploadList)

    const atlas = this.data.dynamic.atlas.concat(urlList)
    this.setData({
      'dynamic.atlas': atlas
    })
    wx.hideLoading()
  },
  // 上传视频
  async bindVideoUpload() {
    const {
      tempFiles
    } = await wx.chooseMedia({
      mediaType: ['video'],
      count: 1
    })
    console.log(tempFiles)
    const tempFilePath = tempFiles[0].tempFilePath
    const thumbTempFilePath = tempFiles[0].thumbTempFilePath
    const videoUrl = await uploadFileAsync(tempFilePath)
    const videoCover = await uploadFileAsync(thumbTempFilePath)
    console.log(videoUrl)
    console.log(videoCover)
    this.setData({
      'dynamic.videoUrl': videoUrl,
      'dynamic.videoCover': videoCover
    })
  },
  // 删除图片
  clareImage(e) {
    console.log(e)
    const index = e.currentTarget.dataset.index
    console.log(index)
    const atlas = this.data.dynamic.atlas.filter((item, i) => index != i)
    this.setData({
      'dynamic.atlas': atlas
    })
  },
  // 删除视频
  clareVideo() {
    this.setData({
      'dynamic.videoCover': '',
      'dynamic.videoUrl': '',
    })
  },
  // 选择框
  async bindPickerChange(e) {
    const type = e.currentTarget.dataset.type
    let value = e.detail.value
    if (type == 'type') {
      value++
    }
    if (type == 'isShow') {
      value = Number(value)
    }
    console.log(type, value)
    this.setData({
      [`dynamic.${type}`]: value
    })
  },
  // 发布动态
  async submit() {
    console.log(this.data)
    const {
      address,
      atlas,
      desc,
      isShow,
      type,
      videoUrl,
      videoCover,

    } = this.data.dynamic
    const topicList = this.data.topicList

    if (!desc) {
      wx.showToast({
        title: '请输入正文..',
        icon: 'none'
      })
      return
    }
    if (type == 1) {
      if (atlas.length < 1) {
        wx.showToast({
          title: '至少上传一张图片',
          icon: 'none'
        })
        return
      }
    }
    if (type == 2) {
      if (!videoCover || !videoUrl) {
        wx.showToast({
          title: '请上传视频..',
          icon: 'none'
        })
        return
      }
    }
    wx.showLoading({
      title: '发布中...',
    })
    console.log(topicList)
    console.log(isShow)
    const topicId = topicList.map(item => item.id)

    const addRes = await postDynamicApi({
      address,
      atlas,
      desc,
      isShow,
      type,
      videoUrl,
      videoCover,
      topicId
    })
    console.log(addRes)

    if (addRes.code == 200) {
      wx.showToast({
        title: addRes.message,
        icon: 'success',
        mask: true
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)

    } else {
      wx.showToast({
        title: addRes.message,
        icon: 'none'
      })
    }

  },
  // 话题圈回调事件
  topicEvent(item) {
    // console.log(item)
    const topicList = this.data.topicList
    const exists = topicList.some(i => i.id === item.id);
    // console.log(exists)
    if (!exists) {
      topicList.push(item)
    }
    this.setData({
      topicList: topicList
    })

  },
  // 删除某个选中的话题
  clareTopic(e) {
    console.log(e)
    const id = e.currentTarget.dataset.id
    let topicList = this.data.topicList
    topicList = topicList.filter(item => item.id != id)
    this.setData({
      topicList
    })
  },
  // 跳转话题圈
  gotoTopic() {
    wx.navigateTo({
      url: '../../home/topic/index?isBack=true',
    })
  },
  // 获取地理位置
  async getAddeess() {
    console.log(1)
    const {
      type,
      city,
      address
    } = await wx.choosePoi()
    if (type === 1) {
      this.setData({
        'dynamic.address': city
      })
    } else
    if (type === 2) {
      this.setData({
        'dynamic.address': address
      })
    } else {
      this.setData({
        'dynamic.address': ''
      })
    }

  }

})